<?php

namespace App\Controllers;

use App\Models\Article_model;
use App\Models\Relation_model;

class article extends BaseController
{
    // 构造函数
    /**
     * @var Article_model
     */
    private $article_model;

    public function __construct()
    {
        // 父类 自动使用默认配置组连接数据库
        parent::__construct();
        $this->article_model = new Article_model();
    }

    public function index()
    {
        // 分页类配置
        $page = $this->request->getGet('page');
        $per_page = $this->request->getGet('per_page');

        $page = is_null($page) ? 0 : $page;
        $per_page = is_null($per_page) ? 4 : $per_page;
        $data['base_url'] = base_url() . '/article/view/';
        $data['total_rows'] = $this->article_model->db->table($this->article_model->table)->countAll();
        $data['per_page'] = $per_page;
        $data['page'] = $page;
        $data['article'] = $this->article_model->get_articles(FALSE, $per_page, $page);
        // 构造用户数据
        foreach ($data["article"] as &$article) {
            $u_id = $article["u_id"];
            $article["user_data"] = $this->user_model->getUser("id", $u_id, ["id", "username", "avatar"]);
        }
        print_r($this->json_result(true, '返回成功', $data));
    }

    public function sort_zan(){
        // 分页类配置
        $page = $this->request->getGet('page');
        $per_page = $this->request->getGet('per_page');
        $page = is_null($page) ? 0 : $page;
        $per_page = is_null($per_page) ? 4 : $per_page;
        $data['base_url'] = base_url() . '/article/view/';

        $data['total_rows'] = $this->article_model->db->table($this->article_model->table)->countAll();
        $data['per_page'] = $per_page;
        $data['page'] = $page;
        $data['article'] = $this->article_model->get_articles(FALSE, $per_page, $page,FALSE,"zan_count");
        // 构造用户数据
        foreach ($data["article"] as &$article) {
            $u_id = $article["u_id"];
            $article["user_data"] = $this->user_model->getUser("id", $u_id, ["id", "username", "avatar"]);
        }
        print_r($this->json_result(true, '返回成功', $data));

    }

    public function my_articles()
    {
        $data['article'] = [];
        if (!$this->is_login()) {
            print_r($this->json_result(false, '未登录', $data));
            return;
        }
        $u_id = $this->session->get("u_id");
        $page = $this->request->getGet('page');
        $per_page = $this->request->getGet('per_page');

        $page = is_null($page) ? 0 : $page;
        $per_page = is_null($per_page) ? 4 : $per_page;
        $data['base_url'] = base_url() . '/article/view/';
        $data['total_rows'] = $this->article_model->db->table($this->article_model->table)->Where("u_id", $u_id)->countAll();
        $data['per_page'] = $per_page;
        $data['page'] = $page;
        $data['article'] = $this->article_model->get_articles(FALSE, $per_page, $page, ["u_id"=>$u_id]);
        //构造用户数据
        foreach ($data["article"] as &$article) {
            $u_id = $article["u_id"];
            $article["user_data"] = $this->user_model->getUser("id", $u_id, ["id", "username", "avatar"]);
        }
        print_r($this->json_result(true, '返回成功', $data));
    }

    public function view()
    {
        $slug = $this->request->getGet("slug");
        $data["article"] = [];
        if (!$slug) {
            print_r($this->json_result(true, '没有索引', $data));
            return;
        }
        $slug = urldecode($slug);
        $data['article'] = $this->article_model->get_articles($slug)->getResult();
        if (empty($data['article'])) {
            print_r($this->json_result(false, '没有这个博文', $data));
            return;
        }
        $data['article']["article"]["user_data"] = $this->user_model->getUser("id", $data['article']["u_id"], ["id", "username", "avatar"]);
        print_r($this->json_result(true, '查找成功', $data));
    }

    // 搜索
    public function search_articles()
    {
        $keywords = $this->request->getGet("keywords");
        $data["article"] = [];
        if (!$keywords) {
            print_r($this->json_result(true, '没有索引', $data));
            return;
        }
        $keywords = urldecode($keywords);

        $data["article"] = $this->article_model->search_articles($keywords)->getResult();
        if (empty($data['article'])) {
            print_r($this->json_result(false, '没有找到相关博文', $data));
            return;
        }

        // 构造用户数据
        foreach ($data["article"] as $article) {
            $u_id = $article->u_id;
            $article->user_data = $this->user_model->getUser("id", $u_id, ["id", "username", "avatar"]);
        }

        print_r($this->json_result(true, '查找成功', $data));
    }

    // 创建博文
    public function create()
    {
        $data['u_id'] = '';
        $article_info = $this->get_data_info();
        if (!$article_info) {
            print_r($this->json_result(false, '请登录或者未填写表单', $data));
            return;
        }
        $data["u_id"] = $article_info["u_id"];
        if ($this->article_model->create($article_info)) {
            print_r($this->json_result(true, '创建成功', $data));
        } else {
            print_r($this->json_result(false, '创建失败', $data));
        }
    }

    public function get_data_info()
    {
        if (!$this->is_login()) {
            return false;
        }
        $title = $this->request->getPost('title');
        $body = $this->request->getPost('body');
        $u_id = $this->session->get('u_id');

        if ($title && $body)
            return array(
                'u_id' => $u_id,
                'title' => $title,
                'body' => $body,
            );
        else
            return false;
    }

    // 编辑博文
    public function edit()
    {
        $data['u_id'] = '';
        $article_info = $this->get_data_info();
        if (!$article_info) {
            print_r($this->json_result(false, '请登录或者未填写表单', $data));
            return;
        }
        $article_id = $this->request->getPost('article_id');

        $this->article_model->update_article($article_id, $article_info);
    }

    // 删除博文
    public function delete()
    {
        $article_id = $this->request->getGet('article_id');

        $data["article"] = [];
        $data["id"] = '';
        if (!$this->is_login() || !$article_id) {
            print_r($this->json_result(false, '请登录', $data));
            return;
        }
        $u_id = $this->session->get("u_id");
        if ($this->article_model->delete_articles($article_id, $u_id)) {
            print_r($this->json_result(true, '删除成功', $data));
        } else
            print_r($this->json_result(false, '数据库删除失败', $data));
    }

    public function thumbs_up()
    {
        $data['errors'] = '';
        $article_id = $this->request->getGet('article_id');
        $u_id = $this->session->get("u_id");
        if (!$this->is_login() || !$article_id) {
            print_r($this->json_result(false, '请登录或传入文章id', $data));
            return;
        }
        // 检查文章是否存在
        if (!$this->article_model->check_is_exist($article_id)) {
            print_r($this->json_result(false, '文章不存在', $data));
            return;
        }
        $relation_model = new Relation_model();
        // 不能重复点赞
        if ($relation_model->check_is_exist($u_id, $article_id, "thumbs_up")) {
            print_r($this->json_result(false, '重复点赞', $data));
            return;
        }
        try {
            // 开始点赞
            $relation_model->db->transStart();
            if (!$relation_model->add_new($u_id, $article_id, "thumbs_up")) {
                print_r($this->json_result(false, '点赞失败', $data));
                return;
            }
            $builder = $relation_model->db->table("article");

            $builder->set('zan_count', 'zan_count+1', FALSE);
            $builder->where("id", $article_id);
            $builder->update();
            $result = $this->article_model->get_article_by_id($article_id);
            if(!$result)
            {
                print_r($this->json_result(false, '用户不存在', $data));
                return;
            }
            $anchor_id = $result["u_id"];
            $builder = $relation_model->db->table("users");
            $builder->set('zan_count', 'zan_count+1', FALSE);
            $builder->where("id", $anchor_id);
            $builder->update();
        } catch (\Exception $exception) {
            print_r($this->json_result(false, '点赞失败', $data));
            return;
        }
        $relation_model->db->transComplete();
        print_r($this->json_result(true, '点赞成功', $data));
    }

    public function unthumbs_up()
    {
        $data['errors'] = '';
        $article_id = $this->request->getGet('article_id');
        $u_id = $this->session->get("u_id");
        if (!$this->is_login() || !$article_id) {
            print_r($this->json_result(false, '请登录或传入文章id', $data));
            return;
        }
        // 检查文章是否存在
        if (!$this->article_model->check_is_exist($article_id)) {
            print_r($this->json_result(false, '文章不存在', $data));
            return;
        }
        $relation_model = new Relation_model();

        // 没点赞不能取消
        if (!$relation_model->check_is_exist($u_id, $article_id, "thumbs_up")) {
            print_r($this->json_result(false, '文章未点赞', $data));
            return;
        }

        try {
            // 开始操作数据库
            $relation_model->db->transStart();
            if (!$relation_model->delete_old($u_id, $article_id, "thumbs_up")) {
                print_r($this->json_result(false, '取消赞失败', $data));
                return;
            }
            $builder = $relation_model->db->table("article");
            $builder->set('zan_count', 'zan_count-1', FALSE);
            $builder->where("id", $article_id);
            if (!$builder->update()) {
                print_r($this->json_result(false, '取消赞失败', $data));
                return;
            }

            $anchor_id = $this->article_model->get_article_by_id($article_id)["u_id"];
            $builder = $relation_model->db->table("users");
            $builder->set('zan_count', 'zan_count-1', FALSE);
            $builder->where("id", $anchor_id);
            if (!$builder->update()) {
                print_r($this->json_result(false, '取消赞失败', $data));
                return;
            }
        } catch (\Exception $exception) {
            print_r($this->json_result(false, '取消赞失败', $data));
            return;
        }
        $relation_model->db->transComplete();
        print_r($this->json_result(true, '取消赞成功', $data));
    }
}